//
//  YTBleContentView.m
//  YUNT
//
//  Created by 梁炜东 on 2017/11/22.
//  Copyright © 2017年 梁炜东. All rights reserved.
//

#import "YTBleContentView.h"
#import "YTBleManager.h"
#import <CoreBluetooth/CoreBluetooth.h>

@interface YTBleContentView ()<UIGestureRecognizerDelegate, UITableViewDelegate, UITableViewDataSource>
@property(nonatomic, copy)BleBlock block;
@property(nonatomic, strong)YTBleManager *bleManager;
@property(nonatomic, strong)UIView *bgView;
@property(nonatomic, strong)UIButton *closeBtn;
@property(nonatomic, strong)UILabel *titleLabel;
@property(nonatomic, strong)UIView *tipsBgView;
@property(nonatomic, strong)UILabel *tipsLabel;
@property(nonatomic, strong)UIActivityIndicatorView *activityIndicatorView;
@property(nonatomic, strong)UIButton *enterCameraBtn;
@property(nonatomic, strong)UITableView *myTableView;
@property(nonatomic, strong)NSMutableArray *data;
@end

@implementation YTBleContentView

-(void)closeAction:(UIButton *)sender
{
    [self removeFromSuperview];
}
-(void)enterCameraAction:(UIButton *)sender
{
    self.block();
    [self removeFromSuperview];
}
-(void)tapAction:(UITapGestureRecognizer *)tap
{
    [self removeFromSuperview];
}
-(void)p_reload
{
    [[YTBleManager shareModel] reloadBleListBlock:^(NSMutableArray *devices) {
        self.data = devices;
        if (self.data && self.data.count > 0)
        {
            _myTableView.hidden = NO;
            _tipsBgView.hidden = YES;
            [_myTableView reloadData];
        }else
        {
            _myTableView.hidden = YES;
            _tipsBgView.hidden = NO;
        }
    }];
}
-(instancetype)initWithBlock:(BleBlock)block
{
    self = [super init];
    if (self)
    {
        self.block = block;
        self.frame = KeyWindow.bounds;
        [self p_reload];
        UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction:)];
        tap.numberOfTapsRequired = 1;
        tap.numberOfTouchesRequired = 1;
        tap.delegate = self;
        [self addGestureRecognizer:tap];
        
        [self addSubview:self.bgView];
        [_bgView addSubview:self.titleLabel];
        [_bgView addSubview:self.closeBtn];
        [_bgView addSubview:self.myTableView];
        [_bgView addSubview:self.tipsBgView];
        [_tipsBgView addSubview:self.tipsLabel];
        [_tipsBgView addSubview:self.activityIndicatorView];
        [_bgView addSubview:self.enterCameraBtn];
    }
    return self;
}
-(void)layoutSubviews
{
    [super layoutSubviews];
    [self p_makeConstraints];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 39;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    cell.backgroundColor = [UIColor clearColor];
    cell.layer.borderWidth = 0.5;
    cell.layer.borderColor = YTColorAlpha(80, 80, 80, 0.3).CGColor;
    CBPeripheral *peripheral = self.data[indexPath.row];
//    cell.textLabel.text  = peripheral.identifier.UUIDString;
    NSString *name = nil;
    if (!peripheral.name || [peripheral.name isEqualToString:@""])
    {name = @"NO Name";}else
    {name = peripheral.name;}
    cell.textLabel.text  = name;
    return cell;
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [SVProgressHUD setDefaultStyle:SVProgressHUDStyleDark];
    [SVProgressHUD showInfoWithStatus:@"谁在点，是不是你，是不是你尬光,点击\"进入相机\"，么么哒"];
    CBPeripheral *peripheral = self.data[indexPath.row];
    [[YTBleManager shareModel] connectPeripheral:peripheral];
}

-(void)p_makeConstraints
{
    if (SharedApplication.statusBarOrientation == UIInterfaceOrientationPortrait ||
        SharedApplication.statusBarOrientation == UIInterfaceOrientationPortraitUpsideDown)
    {//竖屏
        [_bgView mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.center.equalTo(self);
            make.height.mas_equalTo(ScreenWidth - 30);
//            make.width.mas_equalTo(260);
            make.width.mas_equalTo(ScreenWidth - 70);
        }];
    }else
    {//横屏
        //只能竖屏 不能横屏
    }
    [_titleLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.leading.trailing.equalTo(_bgView);
        make.height.mas_equalTo(39);
    }];
    [_closeBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.top.bottom.equalTo(_titleLabel);
        make.width.mas_equalTo(70);
    }];
    NSString *message = _tipsLabel.text;
    CGSize maxSize = CGSizeMake(ScreenWidth-50-80, MAXFLOAT);
    NSDictionary *dict = @{NSFontAttributeName : _tipsLabel.font};
    // 如果计算出的文字范围超出了指定的范围,返回的就是指定的范围
    CGSize size =  [message boundingRectWithSize:maxSize options:NSStringDrawingUsesLineFragmentOrigin attributes:dict context:nil].size;
    [_tipsBgView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.mas_bottom);
        make.leading.trailing.equalTo(_bgView);
        make.height.mas_equalTo(size.height + 20);
    }];
    [_tipsLabel mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.bottom.equalTo(_tipsBgView);
        make.leading.equalTo(_tipsBgView).offset(10);
        make.trailing.equalTo(_tipsBgView).offset(-70);
    }];
    [_activityIndicatorView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.equalTo(_tipsLabel.mas_trailing).offset(0);
        make.top.bottom.trailing.equalTo(_tipsBgView);
    }];
    [_enterCameraBtn mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.leading.trailing.bottom.equalTo(_bgView);
        make.height.equalTo(_titleLabel);
    }];
    [_myTableView mas_remakeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(_titleLabel.mas_bottom);
        make.leading.trailing.equalTo(_bgView);
        make.bottom.equalTo(_enterCameraBtn.mas_top);
    }];
}
-(UIView *)bgView
{
    if (!_bgView)
    {
        _bgView = [[UIView alloc] init];
        _bgView.backgroundColor = YTColorAlpha(190, 190, 190, 0.9);
        _bgView.layer.cornerRadius = 10;
        _bgView.layer.masksToBounds = YES;
    }
    return _bgView;
}
-(UIButton *)closeBtn
{
    if (!_closeBtn)
    {
        _closeBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _closeBtn.backgroundColor = [UIColor clearColor];
        [_closeBtn setTitle:Language(@"关闭") forState:UIControlStateNormal];
        [_closeBtn setTitleColor:YTColor(92, 204, 225) forState:UIControlStateNormal];
        _closeBtn.titleLabel.font = [UIFont systemFontOfSize:15];
        [_closeBtn addTarget:self action:@selector(closeAction:) forControlEvents:UIControlEventTouchUpInside];
    }
    return _closeBtn;
}
-(UILabel *)titleLabel
{
    if (!_titleLabel)
    {
        _titleLabel = [[UILabel alloc] init];
        _titleLabel.backgroundColor = [UIColor clearColor];
        _titleLabel.textColor = [UIColor blackColor];
        _titleLabel.textAlignment = NSTextAlignmentCenter;
        _titleLabel.userInteractionEnabled = YES;
        _titleLabel.text = Language(@"蓝牙");
    }
    return _titleLabel;
}
-(UIView *)tipsBgView
{
    if (!_tipsBgView)
    {
        _tipsBgView = [[UIView alloc] init];
        _tipsBgView.backgroundColor = YTColor(234, 234, 234);
    }
    return _tipsBgView;
}
-(UILabel *)tipsLabel
{
    if (!_tipsLabel)
    {
        _tipsLabel = [[UILabel alloc] init];
        _tipsLabel.backgroundColor = [UIColor clearColor];
        _tipsLabel.textColor = [UIColor blackColor];
        _tipsLabel.textAlignment = NSTextAlignmentLeft;
        _tipsLabel.userInteractionEnabled = YES;
        _tipsLabel.font = [UIFont systemFontOfSize:15];
        _tipsLabel.numberOfLines = 0;
        _tipsLabel.text = Language(@"未搜索到机型,请确认设备已打开,并没有被其他手机连接。");
    }
    return _tipsLabel;
}
-(UIActivityIndicatorView *)activityIndicatorView
{
    if (!_activityIndicatorView)
    {
        _activityIndicatorView = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];
        [_activityIndicatorView startAnimating];
    }
    return _activityIndicatorView;
}
-(UIButton *)enterCameraBtn
{
    if (!_enterCameraBtn)
    {
        _enterCameraBtn = [UIButton buttonWithType:UIButtonTypeCustom];
        _enterCameraBtn.backgroundColor = [UIColor clearColor];
        [_enterCameraBtn setTitle:Language(@"进入相机") forState:UIControlStateNormal];
        [_enterCameraBtn setTitleColor:YTColor(90, 150, 220) forState:UIControlStateNormal];
        _enterCameraBtn.titleLabel.font = [UIFont systemFontOfSize:17 weight:0.5];
        [_enterCameraBtn addTarget:self action:@selector(enterCameraAction:) forControlEvents:UIControlEventTouchUpInside];
        UIView *line = [[UIView alloc] init];
        line.backgroundColor =YTColorAlpha(80, 80, 80, 0.3);
        [_enterCameraBtn addSubview:line];
        [line mas_remakeConstraints:^(MASConstraintMaker *make) {
            make.leading.trailing. top.equalTo(_enterCameraBtn);
            make.height.mas_equalTo(1);
        }];
    }
    return _enterCameraBtn;
}
-(UITableView *)myTableView
{
    if (!_myTableView)
    {
        _myTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];;
        _myTableView.delegate = self;
        _myTableView.dataSource = self;
        _myTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        [_myTableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"UITableViewCell"];
        _myTableView.backgroundColor = [UIColor clearColor];
    }
    return _myTableView;
}
-(BOOL)gestureRecognizer:(UIGestureRecognizer *)gestureRecognizer shouldReceiveTouch:(UITouch *)touch
{
//    if ([NSStringFromClass([touch.view class]) isEqualToString:@"UITableViewCellContentView"] ||
//        [NSStringFromClass([touch.view class]) isEqualToString:@"UILabel"] ||
//        [NSStringFromClass([touch.view class]) isEqualToString:@"UIButton"])
//    {
//        return NO;
//    }
    if ([NSStringFromClass([touch.view class]) isEqualToString:@"YTBleContentView"])
    {
        return YES;
    }else
    {
        return NO;
    }
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    UIResponder * next = [self nextResponder];
    NSMutableString * prefix = @"".mutableCopy;
    
    while (next != nil) {
        NSLog(@"%@%@", prefix, [next class]);
        [prefix appendString: @"--"];
        next = [next nextResponder];
    }
}
@end
